<?php
/**
 * 零起飞-(07FLY-CRM)
 * ==============================================
 * 版权所有 2015-2028   成都零起飞网络，并保留所有权利。
 * 网站地址: http://www.07fly.xyz
 * ----------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ==============================================
 * WorkflowBusinessor: kfrs <goodkfrs@QQ.com> 574249366
 * Date: 2019-10-3
 */

namespace app\workflow\logic;

use think\Db;
use think\Request;

/**
 * 业务关联表=》逻辑层
 */
class WorkflowBusiness extends WorkflowBase
{


    /**
     * 业务关联表=>列表
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int|mixed $paginate
     * @return
     */
    public function getWorkflowBusinessList($where = [], $field = true, $order = '', $paginate = DB_LIST_ROWS)
    {
        $list = $this->modelWorkflowBusiness->getList($where, $field, $order, $paginate)->toArray();
        if ($paginate === false) $list['data'] = $list;
        foreach ($list['data'] as &$row) {
            $row['apply_user_name'] = $this->modelSysUser->getValue(['id' => $row['create_user_id']], 'realname');
            $row['business_type_name'] = $this->modelWorkflowBusinessType->getValue(['business_type' => $row['business_type']], 'name');
            $row['business_info'] = $this->serviceWorkflowBusiness->getBusinessTypeInfo($row['business_type'], $row['business_id']);
            $row['isover'] = $this->getOverStatus($row['workflow_is_over']);
        }
        return $list;
    }

    /**
     * 业务关联表=>添加=>对接其它模块添加
     * @param array $data
     * @return array
     */
    public function workflowAddInterface($data = [])
    {
        $validate_result = $this->validateWorkflowBusiness->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateWorkflowBusiness->getError()];
        }
        //0、根据业务表类型=》获得流程模板参数
        if(empty($data['workflow_id'])){
            $wfid = $this->logicWorkflow->getBusinessWorkflow($data['business_type']);
            if ($wfid == 0) {
                return [RESULT_ERROR, '未找到审批流程模板~请选择流程模板'];
                exit;
            }
        }else{
            $wfid = $data['workflow_id'];
        }

        //获取流程当开启节点
        $curr_node_id = $this->logicWorkflowNode->getWorkflowNodeNext($wfid, 0);//开始节点，0为表示开始结点
        if ($curr_node_id == 0) {
            return [RESULT_ERROR, '审批流程未设置审批节点~'];
            exit;
        }

        //检查处理人信息
        //$curr_node_id=当前节点
        //apply_user_id=业务表申请人
        $apply_user_id = empty($data['apply_user_id']) ? SYS_USER_ID : $data['apply_user_id'];
        $create_user_id = empty($data['create_user_id']) ? SYS_USER_ID : $data['create_user_id'];
        $dealinfo = $this->logicWorkflowNode->getWorkflowNodeDealInfo($curr_node_id, $apply_user_id);
        if (empty($dealinfo['deal_list'])) {
            return [RESULT_ERROR, '获取节点处理人员未找到，查看处理节点处理人是否设置'];
            exit;
        }
        $into_data = [
            'business_type' => $data['business_type'],
            'business_id' => $data['business_id'],
            'workflow_id' => $wfid,
            'curr_node_id' => $curr_node_id,
            'prev_node_id' => 0,
            'apply_user_id' => $apply_user_id,
            'create_user_id' => $create_user_id,
        ];
        //1、生成审批配置表
        $workflow_business_id = $this->modelWorkflowBusiness->setInfo($into_data);//业务表流程配置信息

        //2、生成当前节点处理人信息,
        $next_node_id = $this->logicWorkflowNode->getWorkflowNodeNext($wfid, $curr_node_id);//当前节点下一节点

        foreach ($dealinfo['deal_list'] as $deal) {
            $history_data[] = [
                'workflow_business_id' => $workflow_business_id,
                'business_type' => $data['business_type'],
                'business_id' => $data['business_id'],
                'workflow_id' => $wfid,
                'curr_node_id' => $curr_node_id,
                'next_node_id' => $next_node_id,
                'deal_user_id' => $deal['id'],
                'deal_user_name' => $deal['realname'],
                'sign_type' => $dealinfo['sign_type'],
                'create_user_id' => $create_user_id,
            ];
        }
        //3、增加审批记录表（审批流程记录）
        //$result = $this->logicWorkflowBusinessHistory->workflowBusinessHistoryAdd($history_data);//审批流程记录表
        $result = $this->modelWorkflowBusinessHistory->setList($history_data);// 批量增加 审批流程记录表

        $result && action_log('新增', '新增审核业务关联表' . $data['business_type'] . 'id=' . $data['business_id']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelWorkflowBusiness->getError()];
    }

    /**
     * 业务关联表信息
     * @param array $where
     * @param bool $field
     * @return
     */
    public function getWorkflowBusinessInfo($where = [], $field = true)
    {
        $info = $this->modelWorkflowBusiness->getInfo($where, $field);

        //审批流程节点
        $map['workflow_id'] = ['=', $info['workflow_id']];
        $wflist = $this->modelWorkflowNode->getList($map, "name", 'sort asc', false);
        is_object($wflist) && $wflist = $wflist->toArray();
        $info['workflow_list'] = arr2str(array_column($wflist, 'name'), ' → ');
        $info['curr_node_name'] = $this->modelWorkflowNode->getValue(['id' => $info['curr_node_id']], "name");

        //审批历史记录
        $condition['workflow_business_id'] = $info['id'];
        $history_list = $this->modelWorkflowBusinessHistory->getList($condition, '', 'id desc', false);
        foreach ($history_list as &$row) {
            $row['curr_node_name'] = $this->modelWorkflowNode->getValue(['id' => $row['curr_node_id']], 'name');
            $row['deal_status_name'] = $this->modelWorkflowBusinessHistory->deal_status($row['deal_status'])['name'];
            $row['sign_type_name'] = $this->modelWorkflowBusinessHistory->sign_type_name($row['sign_type']);

            //判断当前处理人员
            if($info['id']==$row['workflow_business_id'] && $info['curr_node_id']==$row['curr_node_id'] ){
                $info['deal_user_name']=$row['deal_user_name'];
            }

        }
        $info['workflow_business_history'] = $history_list;

        $info['business_type_name']=$this->modelWorkflowBusinessType->getValue(['business_type'=>$info['business_type']],'name');
        $info['business_info']=$this->serviceWorkflowBusiness->getBusinessTypeInfo($info['business_type'],$info['business_id']);

        return $info;

    }


    /**流程关联业务=》审批执行
     * 处理动作有：0=待处理,1=通过，2=拒绝，3=转发
     * @param array $data
     * @return array
     * Author: 开发人生 goodkfrs@qq.com
     * Date: 2022/2/18 0018 16:38
     */
    public function workflowBusinessApproval($data = [])
    {
        //审批的记录的ID号
        if (empty($data['wbhid'])) {
            return [RESULT_ERROR, '审批业务id号不存在'];
            exit;
        }
        switch ($data['deal_status']) {
            case '1'://同意
                $this->workflowBusinessApprovalPass($data);
                break;
            case '2'://拒绝
                $this->workflowBusinessApprovalReject($data);
                break;
            case '3'://转交
                $this->workflowBusinessApprovalTransfer($data);
                break;
        }
        $up_his = [
            'deal_status' => $data['deal_status'],
            'suggestion_feedback' => $data['suggestion_feedback'],
            'deal_time' => format_time(),
        ];
        $result = $this->modelWorkflowBusinessHistory->updateInfo(['id' => $data['wbhid']], $up_his);
        $result && action_log('审批', '审批业务表操作，history_id=' . $data['wbhid']);
        return $result ? [RESULT_SUCCESS, '添加成功'] : [RESULT_ERROR, $this->modelWorkflowBusinessHistory->getError()];
    }

    /**
     * 审批》同意操作
     * 处理动作有：0=待处理,1=通过，2=拒绝，3=转发
     * @param array $data
     * @return mixed
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/11/24 0024
     */
    public function workflowBusinessApprovalPass($data = [])
    {
        $info = $this->logicWorkflowBusinessHistory->getWorkflowBusinessHistoryInfo(['id' => $data['wbhid']]);

        $wbinfo = $this->modelWorkflowBusiness->getInfo(['id' => $info['workflow_business_id']]);


        //本次添加移交下一节点=》为上次下一节点
        $curr_node_id = $info['next_node_id'];

        // 当前节点（下节点） 表示为最后一节点
        if ($curr_node_id == 0) {

            $is_over = $this->checkWorkflowBusinessSign($info['workflow_business_id'], $info['curr_node_id'], $info['deal_user_id']);
            if ($is_over <= 0) {

                //1、结束审批流程配置表
                $this->modelWorkflowBusiness->updateInfo(['id' => $info['workflow_business_id']], $up_bus = ['workflow_is_over' => 1]);//更新流程配置表

                //2、更新业务表信息,驳回
                // status=0=临时单，1=待审核，2=审核中，3=已通过，4=被驳回，5=已撤销
                $this->serviceWorkflowBusiness->uptBusinessTypeInfo($info['business_type'], $info['business_id'], 3);
            }

        } else {//添加审批下一节点信息

            //判断当前节点是否是会签，会签要全部完成才进行一节点
            $is_over = $this->checkWorkflowBusinessSign($info['workflow_business_id'], $info['curr_node_id'], $info['deal_user_id']);

            // <=0 表示全部签完需要进入下一节点
            if ($is_over <= 0) {

                //获取当前节点处理人信息
                $dealinfo = $this->logicWorkflowNode->getWorkflowNodeDealInfo($curr_node_id, $wbinfo['apply_user_id']);

                //当前节点下一节点
                $next_node_id = $this->logicWorkflowNode->getWorkflowNodeNext($info['workflow_id'], $curr_node_id);

                foreach ($dealinfo['deal_list'] as $deal) {
                    $history_data = [
                        'workflow_business_id' => $info['workflow_business_id'],
                        'business_type' => $info['business_type'],
                        'business_id' => $info['business_id'],
                        'workflow_id' => $info['workflow_id'],
                        'curr_node_id' => $curr_node_id,
                        'next_node_id' => $next_node_id,
                        'deal_user_id' => $deal['id'],
                        'deal_user_name' => $deal['realname'],
                        'sign_type' => $dealinfo['sign_type'],
                    ];
                    //   print_r($history_data);exit;
                    $result = $this->logicWorkflowBusinessHistory->workflowBusinessHistoryAdd($history_data);//审批流程记录表

                    if ($result[0] == RESULT_ERROR) return $result;

                }

                //更新流程业务配置表
                $up_bus = [
                    'curr_node_id' => $curr_node_id,//当前节点
                    'prev_node_id' => $info['curr_node_id'],//上次节点本次操作的节点
                ];
                $this->modelWorkflowBusiness->updateInfo(['id' => $info['workflow_business_id']], $up_bus);
            }

        }
    }

    /**
     * 审批》拒绝操作
     * 处理动作有：0=待处理,1=通过，2=拒绝，3=转发
     * 1、反回申请人员重新提交
     * 2、返回上一步重新审批
     * @param array $data
     * @return mixed
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/11/24 0024
     */
    public function workflowBusinessApprovalReject($data = [])
    {
        //当前审指记录
        $info = $this->logicWorkflowBusinessHistory->getWorkflowBusinessHistoryInfo(['id' => $data['wbhid']]);

        //1、判断是返回一节点重批，还是返回修改重提
        if ($data['reject_step'] == 0) {

            //1、审批配置表，结束
            $up_bus = ['workflow_is_over' => 1];
            $this->modelWorkflowBusiness->updateInfo(['id' => $info['workflow_business_id']], $up_bus);

            //2、更新业务表信息,驳回
            // 业务状态：status=0=临时单，1=待审核，2=审核中，3=已通过，4=被驳回，5=已撤销
            $this->serviceWorkflowBusiness->uptBusinessTypeInfo($info['business_type'], $info['business_id'], 4);

        } else if ($data['reject_step'] == '1') {

            $map['workflow_business_id'] = ['=', $info['workflow_business_id']];
            $map['next_node_id'] = ['=', $info['curr_node_id']];//当前步为上一条审批下一步

            $prevInfo = $this->modelWorkflowBusinessHistory->getInfo($map);
            is_object($prevInfo) && $prevInfo = $prevInfo->toArray();

            unset($prevInfo['id']);
            unset($prevInfo['deal_status']);
            unset($prevInfo['deal_time']);
            unset($prevInfo['suggestion_feedback']);
            unset($prevInfo['create_time']);
            unset($prevInfo['update_time']);
            $prevInfo['create_user_id'] = $prevInfo['deal_user_id'];//当前处理人操作
            $this->modelWorkflowBusinessHistory->setInfo($prevInfo);
        }

        //3、本业务流程当前节点全部结束，会签特别处理点
        $condition['workflow_business_id']=$info['workflow_business_id'];
        $condition['business_type']=$info['business_type'];
        $condition['business_id']=$info['business_id'];
        $condition['workflow_id']=$info['workflow_id'];
        $condition['curr_node_id']=$info['curr_node_id'];
        $this->modelWorkflowBusinessHistory->setFieldValue($condition,'deal_status',3);

    }

    /**
     * 审批》转交操作
     * 处理动作有：0=待处理,1=通过，2=拒绝，3=转发
     * 1、反回申请人员重新提交
     * 2、返回上一步重新审批
     * @param array $data
     * @return mixed
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/11/24 0024
     */
    public function workflowBusinessApprovalTransfer($data = [])
    {
        $prevInfo = $this->modelWorkflowBusinessHistory->getInfo(['id' => $data['wbhid']]);
        is_object($prevInfo) && $prevInfo = $prevInfo->toArray();
        unset($prevInfo['id']);
        unset($prevInfo['deal_status']);
        unset($prevInfo['deal_status']);
        unset($prevInfo['deal_time']);
        unset($prevInfo['suggestion_feedback']);
        unset($prevInfo['create_time']);
        unset($prevInfo['update_time']);
        $prevInfo['deal_user_id'] = $data['forward_user_id'];//转交id
        $prevInfo['deal_user_name'] = $data['forward_user_name'];//转交name
        $prevInfo['create_user_id'] = $prevInfo['deal_user_id'];//当前处理人操作
        $this->modelWorkflowBusinessHistory->setInfo($prevInfo);
    }

    /**
     * 查询当前审批表=》当前节点会签人数（未处理）
     * @param $workflow_business_id
     * @param $curr_node_id
     * @return mixed
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/11/24 0024
     */
    public function checkWorkflowBusinessSign($workflow_business_id, $curr_node_id,$curr_user_id=SYS_USER_ID)
    {
        $cnt = 0;
        $signMap['workflow_business_id'] = ['=', $workflow_business_id];
        $signMap['curr_node_id'] = ['=', $curr_node_id];
        $signMap['deal_status'] = ['=', 0];// 0=还没有处理
        $signMap['sign_type'] = ['=', 3];// 3=多人会签 .还没有处理
        $signMap['deal_user_id'] = ['<>', $curr_user_id];// 排除当前操作人
        $cnt = $this->modelWorkflowBusinessHistory->stat($signMap, "count");
        return $cnt;
    }

    /**
     * 获取列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where=[];

        if(!empty($data['listtype'])){
            if($data['listtype']=='self'){
                $where['deal_user_id'] = ['=', SYS_USER_ID];
            }
        }

        //业务申请人
        if(isset($data['apply_user_id'])){
            if (!empty($data['apply_user_id']) || is_numeric($data['apply_user_id']) === true) {
                $where['apply_user_id'] = ['=', $data['apply_user_id']];
            }
        }

        //关键字查
        !empty($data['keywords']) && $where['deal_user_name'] = ['like', '%' . $data['keywords'] . '%'];

        //处理状态
        if (!empty($data['over_status']) || is_numeric($data['over_status']) === true) {
            $where['workflow_is_over'] = ['=', $data['over_status']];
        }

        //类型
        if (!empty($data['business_type'])) {
            $where['business_type'] = ['=', $data['business_type']];
        }

        //创建时间
        if (!empty($data['create_rangedate'])) {
            $range_date = str2arr($data['create_rangedate'], "-");
            foreach ($range_date as &$date){
                $date=strtotime($date);
            }
            $where['create_time'] = ['between', $range_date];
        }



        return $where;
    }

    /**
     * 获取排序条件
     */
    public function getOrderBy($data = [])
    {
        $order_by = "";
        if (!empty($data['orderField'])) {
            $orderField = $data['orderField'];
            $orderDirection = $data['orderDirection'];
        } else {
            $orderField = "";
            $orderDirection = "";
        }
        if ($orderField == 'by_link') {
            $order_by = "link_time $orderDirection";
        } else if ($orderField == 'by_next') {
            $order_by = "next_time $orderDirection";
        } else if ($orderField == 'by_nodays') {
            $order_by = "nodays $orderDirection";
        } else {
            $order_by = "id desc";
        }
        return $order_by;
    }

    /**
     * 审批处理状态
     * @param null $key
     * @return mixed
     * Author: 开发人生 goodkfrs@qq.com
     * Date: 2022/2/18 0018 16:39
     */
    public function  getOverStatus($key=null){
        return $this->modelWorkflowBusiness->is_over_status($key);
    }

}
